package com.share.common.utils;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class HttpUtilV2 {
    public static int connectTimeOut = 3000;//连接事件
    public static int readTimeout = 3000;//读时间
    // 创建一个HostnameVerifier
    static HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
            // 直接返回true，意味着接受任何主机名
            return true;
        }
    };
    static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    }};


    public static String get(String url, Map<String, String> getParam, Map<String, String> header, Integer _readTimeout, Integer _connectTimeOut) throws IOException {
        // 发送 GET 请求
        //传递的参数
        Map<String, Object> tmpMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(getParam)) {
            tmpMap.putAll(getParam);
        }

        //url参数
        Map<String, String> urlMap = ParamUtil.kvToMap(url);
        if (!CollectionUtils.isEmpty(urlMap)) {
            tmpMap.putAll(urlMap);
        }

        String s = ParamUtil.mapToKv(tmpMap);
        if (!StringUtils.isEmpty(s)) {
            if (url.indexOf("?") > 0) {
                url = url.split("\\?")[0] + "?" + s;
            } else {
                url = url + "?" + s;
            }
        }

        HttpURLConnection con = createConnection(url, header, "GET", _readTimeout, _connectTimeOut);
        con.setDoOutput(true);

        return handleResponse(con);
    }

    public static String post(String url, String jsonStr, Map<String, String> header, Integer _readTimeout, Integer _connectTimeOut) throws IOException {
        HttpURLConnection con = createConnection(url, header, "POST", _readTimeout, _connectTimeOut);
        con.setDoOutput(true);

        // 发送 PUT 请求
        if (!StringUtils.isEmpty(jsonStr)) {
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonStr.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
        }

        return handleResponse(con);
    }


    private static HttpURLConnection createConnection(String url, Map<String, String> header, String method, Integer _readTimeout, Integer _connectTimeOut) throws IOException {
        HttpURLConnection con = null;

        if (url.startsWith("https")) {
            try {
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
                con = (HttpsURLConnection) obj.openConnection();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            URL obj = new URL(url);
            con = (HttpURLConnection) obj.openConnection();
        }


        con.setRequestMethod(method);//请求方式
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");

        //覆盖上面的配置
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (!StringUtils.isEmpty(value)) {
                    con.setRequestProperty(key, value);
                }
            }
        }

        // 读取数据超时时间
        if (_readTimeout == null) {
            _readTimeout = readTimeout;
        }
        con.setReadTimeout(_readTimeout);
        // 连接主机超时时间
        if (_connectTimeOut == null) {
            _connectTimeOut = connectTimeOut;
        }
        con.setConnectTimeout(_connectTimeOut);//连接主机的超时时间  ---链接建立的超时时间,一般是3秒
        con.setReadTimeout(_readTimeout);//读取数据的超时时间---核心参数

        return con;
    }

    private static String handleResponse(HttpURLConnection con) throws IOException {
        int responseCode = con.getResponseCode();
        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line.trim());
                }
            }
            return response.toString();
        } else {
            // 读取错误信息
            try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(con.getErrorStream()))) {
                StringBuilder errorResponse = new StringBuilder();
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                System.out.println("接口调用失败：" + errorResponse.toString());
            }
            return null;
        }
    }

    public static void main(String[] args) {
        String post = null;
        try {
            post = post("https://sfp.safe.baidu.com/sfp/v1/rd", null, null, null, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(post);
    }
}
